package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

import server.MyNapsterServer;

public class ServerGUI extends JFrame implements Runnable{
	private static final long serialVersionUID = 1L;
	private JTextArea log;
	private MyNapsterServer server;
	private static ServerGUI instance;

	public void appendLogMessage(String message){
		log.append(message + "\n");
		log.repaint();
	}
	
	public static ServerGUI getInstance(){
		if (instance == null){
			instance = new ServerGUI();
		}
		return instance;
	}
	
	private ServerGUI(){
		
	}

	@Override
	public void run() {
		this.setSize(800, 600);
		this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));

		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(ABORT);
			}
		});

		final JButton butt = new JButton("Iniciar servidor");
		log = new JTextArea();
		log.setSize(780, 30);		
		log.setText("Log:\n");
		log.setVisible(true);
		
		try {
			server = new MyNapsterServer();			
		} catch (IOException e1) {
			appendLogMessage(e1.getMessage() + "\n");
			return;
		}

		butt.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				try {
					Thread tServer = new Thread(server);
					tServer.start();
					butt.setEnabled(false);
				} catch (Exception e) {
					appendLogMessage(e.getMessage() + "\n");
				}			  
			}
		});

		this.add(butt);
		this.add(log);

		this.setVisible(true);
		
	}
	
	public static void main(String args[]){
		Thread tServerGUI = new Thread(getInstance());
		tServerGUI.start();
	}

}
